package xqp.mq._02_test;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

// 消费者
class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();

        // 创建通道
        Channel channel = connection.createChannel();

        // 每个消费者只能同时处理一条消息
        channel.basicQos(1);

        // 消息处理回调
        com.rabbitmq.client.Consumer callback =new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope, // 信封
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                System.out.println("收到消息"+new String(body));


                //int i =1/0;// 这里报了错但是我没签收
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("交换机 = "+envelope.getExchange());
                System.out.println("队列 = "+envelope.getRoutingKey());
                System.out.println("消息的id = "+envelope.getDeliveryTag());
                System.out.println("消息消费完毕");
                // 手动签收消息
                channel.basicAck(envelope.getDeliveryTag() // 消息的id
                        ,false ); // 是否签收多个消息
            }
        };
        //监听队列
        channel.basicConsume(Producer.NAME_QUEUE, //我们要监听哪个队列
                false, // 是否自动签收   自动签收会出现 如果消息消费失败，可能会导致消息丢失
                callback ); // 处理消息回调
    }
}
